package ua.org.groovy.gs.ui;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;

import ua.org.groovy.gs.botworld.Botworld;

public class GroovyUI extends JComponent {

	private JTextPane scriptArea;
	private GroovyCanvas canvas;
	private Botworld botWorld;
	
	public GroovyUI() {
		setLayout(new BorderLayout());
		
		scriptArea = new GroovyEditorPane();
		scriptArea.setFont(new Font("Monospaced", Font.PLAIN, 12));

		String text = "";
		try {
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(
							getClass().getClassLoader().getResourceAsStream(
									"Default.groovy")));
			String line;
			while ((line = reader.readLine()) != null) {
				text += line + "\n";
			}
		} catch (Exception e) {
			text = null;
			e.printStackTrace();
		}
		
		if (text != null) {
			scriptArea.setText(text);
		} else {
			scriptArea.setText(				
					"agent.onCollision = {println \"hello \" + it } \n" +
					"agent.moveRight()\n" +
					"Thread.sleep(2000)\n" +
					"agent.moveDown()\n" +
					"Thread.sleep(1000)\n" +
					"agent.stop()\n"
					);
		}
		

		JScrollPane scrollPane = new JScrollPane(scriptArea);
		//scrollPane.setViewportView();
		scrollPane.setSize(300, 100);
		scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

		add(scrollPane, BorderLayout.NORTH);
		JButton button = new JButton("Execute");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				new Thread(new Runnable() {
					public void run() {
						String scriptText = GroovyUI.this.scriptArea.getText();
						GroovyUI.this.botWorld.updateDefaultController(scriptText);
					}
				}).start();
			}
		});
		button.setSize(75, 25);

		add(button, BorderLayout.CENTER);
		
		botWorld = new Botworld();
		
		canvas = new GroovyCanvas(botWorld);
		canvas.setSize(400, 200);
		add(canvas, BorderLayout.SOUTH);
	}
	
	
	public void animateCanvas() {
		new Thread(canvas).start();
		botWorld.setWorldHeight(canvas.getHeight());
		botWorld.setWorldWidth(canvas.getWidth());
	}

	public static void main(String... args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				GroovyUI ui = new GroovyUI();

				JFrame frame = new JFrame("Groovy Space");
				frame.setSize(450, 600);
				frame.setResizable(false);
				frame.setLocationRelativeTo(null);
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				frame.add(ui, BorderLayout.CENTER);

				frame.setVisible(true);
				ui.animateCanvas();
				
			}
		});
	}
}
